import jwt from 'jsonwebtoken'
import Admin from '../models/Admin.js'

class Auth {
    constructor() {}

    get m() {
        return async (ctx, next) => {
            let token = ctx.request.header.authorization || ''
            let errMsg = '登录授权失败'
            // 无带token
            if (!token) {
                errMsg = '请先登录'
                throw new global.errs.ServerError(errMsg, 40102)
            }
            try {
                token = token.slice(7)
                var decode = jwt.verify(token, global.config.security.secretKey)
            } catch (error) {
                // token 不合法 过期
                if (error.name === 'TokenExpiredError') {
                    errMsg = '登录已过期，请重新登录'
                }

                throw new global.errs.ServerError(errMsg, 40102)
            }

            if (!decode.scope || decode.scope !== 'endapi') {
                errMsg = '登录授权失败'
                throw new global.errs.ServerError(errMsg)
            }
            
            // 获取管理员信息
            const admin = await Admin.getById(decode.uid, ['id', 'username', 'mobile', 'avatar'])
            if (!admin) {
                throw new global.errs.ServerError('用户不存在')
            }
            ctx.auth = admin

            await next()
        }
    }
}

export default Auth
